package com.example.myapplication;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RateListActivity extends ListActivity {

    private static final String TAG = "RateActivity";
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        String[] list_data = {"one","tow","three","four"};
        ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list_data);
        setListAdapter(adapter);

        handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                // 接收返回的数据项
                if(msg.what==9){
                    List<String> list2 = (List<String>) msg.obj;
                    ListAdapter adapter2 = new ArrayAdapter<String>(RateListActivity.this, android.R.layout.simple_list_item_1,list2);
                    setListAdapter(adapter2);
                }

                super.handleMessage(msg);
            }
        };

        // 启动网络请求线程
        new Thread(() -> {
            try {
                List<String> rateList = new ArrayList<>();

                // 修改1：使用正确的目标URL
                Document doc = Jsoup.connect("https://www.huilvbiao.com/bank/spdb")
                        .timeout(10000)
                        .get();

                // 修改2：根据实际网页结构调整解析逻辑
                Elements rows = doc.select("table tbody tr"); // 假设数据在表格中

                for (Element row : rows) {
                    Elements col1 = row.select("span");
                    Elements cols = row.select("td");
                    if (cols.size() >= 2) {
                        String currency = col1.get(0).text();
                        String rate = cols.get(1).text();
                        rateList.add(currency + " ➤ " + rate);
                        Log.d("ParseData", currency + ": " + rate); // 添加日志
                    }
                }

                Message msg = handler.obtainMessage(5, rateList);
                handler.sendMessage(msg);

            } catch (IOException e) {
                Log.e("NetworkError", "请求失败: " + e.getMessage()); // 错误日志
                e.printStackTrace();
            }
        }).start();
    }
}